/*
* Author: Tuanpm
* Date:08/01/2012
* Idea: Class Home
*/
var trainingIndexXml = '';
var Homeing = 0;
var loadUpdate = 0;

function Home(baseUrl,module,controller, saction,objXml){
	this.module = module;
	this.baseUrl = baseUrl;
	this.controller = controller;
	this.saction = saction;
	this.urlPath = baseUrl + '/' + module + '/' + controller;//Biên public lưu tên module			
	this.loadding = false;
	this.tableContainer = $('#table-container');
	this.strfullTextHome = $('#fullTextHome').val();
	this.sformName = '';
	this.recordName = 'bài giảng'; //Ten ban ghi
	this.dirxml = baseUrl+'/xml/view/search/index.xml';
	this.xmlData = objXml;
	this.HomeBtn = '';
	this.updatecmm = '';
	this.statusUpdateCmmt = function(obj){				
		if($(this.updatecmm).attr('style') == '' || !$(this.updatecmm).attr('style'))		
			$(this.updatecmm).css('width',$(this.updatecmm).outerWidth());
		$(this.updatecmm).val('');
		$(this.updatecmm).removeClass('link-button');
		$(this.updatecmm).addClass('link-button-Homeing');
		loadUpdate = 1;
	}

	this.successUpdateCmmt = function(obj){
		if($(this.updatecmm).attr('style') == '' || !$(this.updatecmm).attr('style'))		
			$(this.updatecmm).css('width',$(this.updatecmm).outerWidth());
		$(this.updatecmm).val('Gửi ý kiến');
		$(this.updatecmm).addClass('link-button');
		$(this.updatecmm).removeClass('link-button-Homeing');
		loadUpdate = 0;
	}	
	var objClass = this;
}
//Remove key
Home.prototype.removekey = function(key){
	shortcut.remove(key);
}

Home.prototype.createdata= function(data,breadcrumbs){
	var self = this
		,shtml='';
	$(".packlink").html(breadcrumbs);
	shtml += '<ul>';
    for(var i = 0; i < data.length; i++){
    	shtml += '<li class="itemli" id="' + data[i]["TD01"] + '">';
		shtml += '<a href="#">';
		shtml += '<img src="'+ data[i]['C_FILENAME_THUMB'] +'" width="127" height="117">';
		shtml += '<p class="title">'+shorttitle(data[i]['TD02'],19)+'</p>';
		shtml += '</a>'
		shtml += '</li>'

        // shtml += '<li class="itemli" title="'+data[i]['TD02']+'">';
        // shtml += '<img width="150" height="100" src="'+ data[i]['C_FILENAME_THUMB'] + '">';
        // // shorttitle
        // shtml += '<label>' + shorttitle(data[i]['TD02'],19);
        // shtml += '</label>';
        // shtml += '<input type="checkbox" value="' + data[i]["TD01"] + '" name="chk_item_id" class="chk_item_id" style="display:none;">';
        // shtml += '</li>';
    }
    shtml += '</ul>';
    $('#table-container').html(shtml);
	self.eventdatalist();
    // self.menuContent();
    // reziseli();
}
Home.prototype.eventdatalist= function(){
	var self = this;
	$('#table-container li.itemli').unbind('click');
   	$('#table-container li.itemli').click(function(event){
   		self.viewTraining($(this).attr('id'));
   	});

   	//pathLink
   	$('.alowclick').unbind('click');
   	$('.alowclick').click(function(){
   		var pktree = $(this).attr('pktree');
   		var obj = $("#left_tree").find('li#'+pktree).find('a:first');   		
   		$(obj).trigger('click');
		$(obj).trigger('dblclick');
   	})
}
function alowclick() {
	$('.alowclick').unbind('click');
	$('.alowclick').click(function(){
		var pktree = $(this).attr('pktree');
		var obj = $("#left_tree").find('li#'+pktree).find('a:first');   		
		$(obj).trigger('click');
		$(obj).trigger('dblclick');
	})
}
Home.prototype.ldmod = function(arrInput){
	var objClass = this;
	if (typeof(arrInput) =='undefined') {
		arrInput = {};
	};
	if(Homeing == 1){		
		return false;		
	}else{
		var objClass = this;	
		objClass.loadding = true;
		var url = objClass.urlPath + '/' + objClass.saction;
		statusProcess();
		var data = {
					type: $('.search_bar #type').val(),
					typehdn: $('.search_bar #typehdn').val(),
					hdnpath: $('.search_bar #hdnpath').val(),
					TD18: $('.search_bar #TD18').val(),
					TD03: $('.search_bar #TD03').val(),
					hdn_record_number_page: $('#hdn_record_number_page').val(),
					hdn_current_page: $('#hdn_current_page').val(),
				};
		$.extend(data, arrInput);
		$.ajax({
			url: url,
			type: "POST",
			dataType: 'json',
			//cache: true,
			data:data,
			success: function(data){
				var arrResult = data.arrResult
					,breadcrumbs = data.breadcrumbs
					,sdocpertotal = "Danh sách này không có dữ liệu";
				if(arrResult == null) arrResult = [];
				objClass.createdata(arrResult,breadcrumbs);
				$('#viewDatafrm').hide();
				//Phan trang du lieu
				$('div.paging').html('');		
				if(arrResult.length >0){
					var iNumberRecord = arrResult[0]['C_TOTAL_RECORD'];
					var numberRow = arrResult.length;
					$('#hdn_order').val(iNumberRecord +1);
					if(numberRow > 0)
						sdocpertotal ="Danh sách có " +numberRow + "/" + iNumberRecord + " "+objClass.recordName+".";
					var data = {iTotalRecord: iNumberRecord,
							iPage: $('#hdn_current_page').val(),
							FuntionName:'pagingModal2',
							iRowOnPage: $('#hdn_record_number_page').val()
					}
					$.ajax({
						url: baseUrl + "/public/ajax/ajax.php",
						type: "POST",
						// cache: true,
						data:data,
						success: function(string){							
							$('div.paging').html(string);			
							var cindex = parseInt($('a.active:eq(0)').html());
							var pre = cindex - 1;
							var nex = cindex + 1
							$('a.pre').removeAttr('onclick');
							$('a.pre').click(function(){								
								objClass.gotopageModal(pre);
							});
							$('a.nex').removeAttr('onclick');
							$('a.nex').click(function(){								
								objClass.gotopageModal(nex);
							});				
							$('a.pageLink').removeAttr('onclick');
							$('a.pageLink').click(function(){								
								objClass.gotopageModal(this.innerHTML);
							});
							$('select#cbo_nuber_record_page').change(function(){																
								objClass.changeNumberRowPerPageModal(this);
							});							
						}
					});
				}
				$('#sdocpertotal').html(sdocpertotal);					
				successProcess();
				$(this.HomeBtn).attr('disable', false);			
				$('form#' + objClass.sformName).show();				
				scrollTop(1)
			}
		});
	}
}
Home.prototype.changeNumberRowPerPageModal = function(obj){
	document.getElementById('hdn_current_page').value = 1;
	this.ldmod();
}
Home.prototype.gotopageModal= function(num){
	document.getElementById('hdn_current_page').value = num;	
	this.ldmod(); 
}

function HomeIndex(baseUrl,module,controller, saction,objXml){
	this.module = module;
	this.baseUrl = baseUrl;
	this.controller = controller;
	this.saction = saction;
	this.urlPath = baseUrl + '/' + module + '/' + controller;
	this.dirxml = this.baseUrl+'/xml/view/search/index.xml';		
	this.sformName = 'IndexDataFrm';
	this.tableContainer = $('#table-container');
	this.strfullTextHome = $('.search_bar #TD18').val();
	this.HomeBtn = $('.search_bar .buttonsearch');
	this.updatecmm = $('form#viewData #updatecmm');
	this.typeTree = $('.search_bar #typehdn').val();
	if(objXml == ''){				
		this.xmlData = new efyXml(this.dirxml);			
	}else{				
		this.xmlData = objXml;
	}
	var objClass = this;		
	$(this.HomeBtn).click(function(){
		objClass.ldmod();
	});	
	this.objTree = new publicTree(this,$('#TD03'), $('#TD03name'), this.baseUrl + '/ajax/index', 'TRAINING');
	this.objTree.loadTreefrm();
	
}

Home.prototype.viewTraining = function(PkDoc){
	var objHome = this;
	var url = this.urlPath + '/view';
		var data = {
			PkDoc: PkDoc,
			typehdn :$('form#IndexDataFrm #typehdn').val()
		};
	$.ajax({
			url: url,
			type: "POST",
			data: data,
			//cache: true,
			//dataType: "json",		
			success: function(string){
				$('form#IndexDataFrm').hide();
				$('div#viewDatafrm').html(string);
				$('div#viewDatafrm').show();
				alowclick();
			}
		});	
		 return !history.pushState;
}

Home.prototype.deletecmmt = function(PkDoc){
	objHome = this;
	var url = this.urlPath + '/deletecmmt';
	var PkComments ='';
	var delimitorElement ='!~~!';
	$('form#viewData input[type=checkbox][name="chk_item_id"]:checked').each(function(){
		PkComments += $(this).val() + delimitorElement;
	});
	PkComments = PkComments.substr(0,PkComments.length - delimitorElement.length);
		// alert(PkComments);
	if(PkComments ==''){
		jAlert('Bạn chưa chọn ý kiến nào để xóa', 'Xóa');
		return false;
	}
	jConfirm('Bạn có chắc chắn muốn xóa những ý kiến này?', 'Xóa hồ sơ', function(r) {
	    if(r){
			var arrdata = {PkComments : PkComments,
							delimitorElement : delimitorElement};
			$.ajax({
				url: url,
				type: "POST",
				data: arrdata,
				cache: true,		
				success: function(string){
					objHome.loadcomment(PkDoc);
				}
			});		
		}
	});

}
Home.prototype.editComment =function(obj,id){
    var objHome = this;
        if($(obj).find('input[name="chk_item_id"]').attr('disabled') =='disabled'){
    	jAlert('Bạn không có quyền sửa ý kiến này!', 'Sửa ý kiến');
		return false;
    }else{
		if(id != ''){
			text = $(obj).find('td:eq(2)').text();
			text = text.substr(1,text.length - 1);
			document.viewData.RC06.value = text;
			$("#RC06").focus();
			$('#PkComment').val(id);
			$('form#viewData input#updatecmm').click(function(){
				objHome.updatecmmt(PkDoc);
			});	
		}
	}
}
Home.prototype.updatecmmt = function(PkDoc){
	objHome = this;
	var PkComment = $('form#viewData #PkComment').val();
	if(loadUpdate == 1){		
		return false;		
	}else{
		var cmmt = $('#RC06').val();
		if(cmmt == '--Ý kiến của bạn--' || cmmt == ''){
			jAlert('Bạn chưa nhập ý kiến nhận xét!', 'Cập nhật');
			document.getElementById("RC06").focus();
			return false;
		}
		jConfirm('Bạn muốn cập nhật ý kiến nhận xét!', 'Cập nhật', function(r){
			if(r){
				objHome.statusUpdateCmmt();
				var url = this.urlPath + '/updatecmmt';
				var data = {
					cmmt: cmmt , PkDoc: PkDoc,PkComment : PkComment
				};
				$.ajax({
						url: url,
						type: "POST",
						// dataType: 'json',
						//cache: true,
						data:data,
						success: function(arrResult){						
							objHome.successUpdateCmmt();
							objHome.loadcomment(PkDoc);
							$('#PkComment').val('');
							document.viewData.RC06.value = '--Ý kiến của bạn--';
						}
					});
				objHome.successUpdateCmmt();
			}
		});
	} 
}
Home.prototype.loadcomment = function(PkDoc){		
	var url = this.urlPath + '/loadcomment';
	var data = {
		PkDoc: PkDoc
	};
	var objClass = this;
	var dirxml = baseUrl+'/xml/view/search/Homecomment.xml';
	$.ajax({
		url: url,
		type: "POST",
		dataType: 'json',
		//cache: true,
		data:data,
		success: function(arrResult){
			if(arrResult == null) arrResult = [];
			xmlHomecomment.exportTable(arrResult,'',$('div#table-comment'),'','viewData',5);
		}
	});
}
Home.prototype.back = function(key){
	$('div#viewDatafrm').hide();
	$('form#IndexDataFrm').show();
	shortcut.remove('Enter');
}
Function.prototype.inheritsFrom = function(parentClsOrObj){
	if (parentClsOrObj.constructor == Function ){
		//Normal Inheritance
        this.prototype = new parentClsOrObj;
        this.prototype.constructor = this;
        this.prototype.parent=parentClsOrObj.prototype;
    }
    else
    {
        //Pure Virtual Inheritance
        this.prototype = parentClsOrObj;
        this.prototype.constructor = this;
        this.prototype.parent = parentClsOrObj;
    }
    return this;
}
HomeIndex.inheritsFrom(Home);

Home.prototype.genTreeHome = function(){
	obj = $("#left_tree");
	obj.jstree({ 
		"plugins" : [ 
			"themes","json_data","ui","crrm","dnd","Home","types","hotkeys","adv_Home", "html_data"
		],
	 	"themes" : {
	            "theme" : "default",
	            "dots" : false,
	            "icons" : true,
	            "url": baseUrl + '/public/efy-js/jsTree/themes/default/style.css'
	    		}
	})
	.bind("loaded.jstree", function (event, data) {
		 $("#HomeNode").click(function () {
		 	$("#left_tree").jstree('close_all', -1);
		 	$("#left_tree").jstree("Home", $('#HomeNodes').val());
		 	 $("#left_tree").jstree("refresh");
		});
		$('#HomeNodes').focus(function() {
			shortcut.remove('Enter');
			document.onkeydown =function(e){
			if(e.which == 13){
				$("#left_tree").jstree('close_all', -1);
				$("#left_tree").jstree("Home", $('#HomeNodes').val());
		 	 	$("#left_tree").jstree("refresh");
			}
		}
	});
		$("#HomeNode").trigger('click');
		$("#HomeNode").trigger('focus');
	})
	.bind("select_node.jstree", function (event, data) { 
			$('#TD03').val(data.rslt.obj.attr("id"));
			if(data.rslt.obj.attr("id") != ''){
				$('#type').attr('checked',false);
			}
			nodeName = data.inst.get_text(data.rslt.obj);
			parentName = data.inst.get_text(data.inst._get_parent(data.rslt.obj));
			var listName = $('#hdnpath').val();
			var listName = listName.split(',');
			if(listName.length > 2){
				for (var i = listName.length - 1; i >= 0; i--){
					if(listName[i] == parentName && parentName != '')
						break;
						listName.pop(listName[i]);
					// else listName.push(data.inst.get_text(data.rslt.obj)); 
				}
				listName = listName.join() +',';
			}
			listName += nodeName + ',';
			$('#hdnpath').val(listName);
            obj.jstree("toggle_node", data.rslt.obj);  
		})
	.delegate("a.jstree-clicked", "click", function (event, data) { 
			event.preventDefault(); 
		})
	.delegate("a","dblclick", function(e) { 						
			var listName = $('#hdnpath').val();
			listName = listName.substr(0,listName.length - 1);
			listName = 'Đường dẫn: ' + listName.replace(/,/g,' -> ');
			$('span#noidungxx').text(listName);
			$('#hdn_current_page').val('1');
			objClass.ldmod();
		});

}
Home.prototype.menuContent = function(){
	var self = this
		,oItem =$('#table-container li.itemli');
	$(oItem).unbind('contextmenu');
	var func = function(e){
		$("div.popup").remove();
	    var obj = $(this);
		$('#table-container li.itemli input[type="checkbox"]').attr('checked',false);
		$(obj).find('input[type="checkbox"]').attr('checked',true);
		markcheck();
      	var htmls = '<div class="popup menuelement"><ul>';
      	htmls += '<li id="viewcontent" class="">Xem chi tiết</li>';
      	htmls += '</ul></div>';
      	$(htmls).appendTo("body")
        	.css("left", e.pageX)
        	.css("top", e.pageY)
        	.show();
	    // Sửa
	    $('.popup li#viewcontent').unbind('click');
	  	$('.popup li#viewcontent').bind("click",function(){
			// $(obj).trigger('click');
			// $('input.viewTraining').trigger('click');
			self.viewTraining();
	  	});
	  	
      	e.preventDefault();
      	return false;
	}
	// Create event
	$(oItem).bind('contextmenu', func);
}
var initBackAndForward = function() {
	  var context = this;
	  this.scroll_forward = $('<div class="ad-forward"></div>');
	  this.scroll_back = $('<div class="ad-back"></div>');
	  this.nav.append(this.scroll_forward);
	  this.nav.prepend(this.scroll_back);
	  var has_scrolled = 0;
	  var thumbs_scroll_interval = false;
	  $(this.scroll_back).add(this.scroll_forward).click(
	    function() {
	      // We don't want to jump the whole width, since an image
	      // might be cut at the edge
	      var width = context.nav_display_width - 50;
	      if(context.settings.scroll_jump > 0) {
	        var width = context.settings.scroll_jump;
	      };
	      if($(this).is('.ad-forward')) {
	        var left = context.thumbs_wrapper.scrollLeft() + width;
	      } else {
	        var left = context.thumbs_wrapper.scrollLeft() - width;
	      };
	      if(context.settings.slideshow.stop_on_scroll) {
	        context.slideshow.stop();
	      };
	      context.thumbs_wrapper.animate({scrollLeft: left +'px'});
	      return false;
	    }
	  ).css('opacity', 0.6).hover(
	    function() {
	      var direction = 'left';
	      if($(this).is('.ad-forward')) {
	        direction = 'right';
	      };
	      thumbs_scroll_interval = setInterval(
	        function() {
	          has_scrolled++;
	          // Don't want to stop the slideshow just because we scrolled a pixel or two
	          if(has_scrolled > 30 && context.settings.slideshow.stop_on_scroll) {
	            context.slideshow.stop();
	          };
	          var left = context.thumbs_wrapper.scrollLeft() + 1;
	          if(direction == 'left') {
	            left = context.thumbs_wrapper.scrollLeft() - 1;
	          };
	          context.thumbs_wrapper.scrollLeft(left);
	        },
	        10
	      );
	      $(this).css('opacity', 1);
	    },
	    function() {
	      has_scrolled = 0;
	      clearInterval(thumbs_scroll_interval);
	      $(this).css('opacity', 0.6);
	    }
	  );
};
function showmodallogin(){
	$('#MB_window').lightbox_me({
    	centered: true, 
    	onLoad: function() { 
        $('#MB_window').find('input:first').focus()
        }
    });
    return false;
}
function readdocument(id){
	var url = this.urlPath + '/view';
	statusProcess();		
	$.ajax({
			url: baseUrl+'/web/index/readdocument',
			type: "POST",
			data: {id: id},
			success: function(string){
				$('div#preview-doc').html(string);				
				successProcess();
			}
	});	
}
function downloaddocument(id) {
	window.open(baseUrl+'/web/index/downloaddocument?id='+id);
}
function notview() {
	jAlert('Bạn không có quyền xem tài liệu này<br>Hãy liên hệ admin quản trị để được ban quyền!', 'Xem tài liệu');
}
function notdownload() {
	jAlert('Bạn không có quyền download tài liệu này<br>Hãy liên hệ admin quản trị để được ban quyền!', 'Tải tài liệu');
}

function viewbycode(code){
	objHome.ldmod({code: code});
}
function viewbyauthor(author){
	objHome.ldmod({author: author});
}